import requests
import re
import pandas as pd
import time
import random
import os


cookies = {
    'sajssdk_2015_cross_new_user': '1',
    'sensorsdata2015jssdkchannel': '%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D',
    'wz_uuid': 'X/1fcfaf081bda08cad7b6089eb6d0d887',
    'Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1750836938',
    'HMACCOUNT': 'CE957E555288C4C9',
    'acw_tc': 'cc7720ac175083880670612144e9df6788f3bace3a1915d380ec3eb01e23e1',
    'ticket': 'eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi54d1R2VWQtYnFMV2Z4RS1OMDNSQkF3LjJHVWRjMzhkRGdTQ0hVbkdNbGpYMFdqdy1hMHlTSnBTX0tBZGRwTjdfd2YwN3JYc3llb0h3S1luSmRPRDBhS3dsOWRGUkxUSU5EY1cwNEp5RWw0Z1NUaHl5bU9RUUtlZEJ3anFMUENoWW5MbFhfaHRCZUxnN3VNZW5qQks0M1FXU1V0cHdpSVUxelRWWjN0LXgyN1VDSW9LRUppTXpldWJHOUQzOG5OUGFCaUNpSmV6MzBwQzJCTVc3T1RsNm8zWG1zYmZhZlpYdW81TGZVbmVtSWs3OUh1YU92TU52UkVtVWxzRWlNSDYxNG5pcXFvOU5sLTJFa0I5ZzFWSHUtcFMudXZjMHJhY1cxNWdpMEdZblVzell6UQ.G5m1b86ceGp_UIbQ2pPz5a6B6rS-f6Bc6vDWTOaCrVH_FKcGJZfgK9oZd0L18QfJibcyMEB9u57jqoMWb_ILmQ',
    '_g_t_': 'e666e04ac8b14146df2b7b4801a6004a',
    'token': 'eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi54d1R2VWQtYnFMV2Z4RS1OMDNSQkF3LjJHVWRjMzhkRGdTQ0hVbkdNbGpYMFdqdy1hMHlTSnBTX0tBZGRwTjdfd2YwN3JYc3llb0h3S1luSmRPRDBhS3dsOWRGUkxUSU5EY1cwNEp5RWw0Z1NUaHl5bU9RUUtlZEJ3anFMUENoWW5MbFhfaHRCZUxnN3VNZW5qQks0M1FXU1V0cHdpSVUxelRWWjN0LXgyN1VDSW9LRUppTXpldWJHOUQzOG5OUGFCaUNpSmV6MzBwQzJCTVc3T1RsNm8zWG1zYmZhZlpYdW81TGZVbmVtSWs3OUh1YU92TU52UkVtVWxzRWlNSDYxNG5pcXFvOU5sLTJFa0I5ZzFWSHUtcFMudXZjMHJhY1cxNWdpMEdZblVzell6UQ.G5m1b86ceGp_UIbQ2pPz5a6B6rS-f6Bc6vDWTOaCrVH_FKcGJZfgK9oZd0L18QfJibcyMEB9u57jqoMWb_ILmQ',
    'sensorsdata2015jssdkcross': '%7B%22distinct_id%22%3A%225091c2a46c8142c19819bb2dc8fa6b6f%22%2C%22first_id%22%3A%22197a6036b5268e-023ab70717f313c-1a525636-1327104-197a6036b5315c3%22%2C%22props%22%3A%7B%22%24search_keyword_id%22%3A%22197a6036b59143b029d5704d89963a1a5256361327104197a6036b5a1bcd%22%2C%22%24search_keyword_id_type%22%3A%22baidu_other_keyword_id%22%2C%22%24search_keyword_id_hash%22%3A4677690145258478%2C%22%24latest_traffic_source_type%22%3A%22%E8%87%AA%E7%84%B6%E6%90%9C%E7%B4%A2%E6%B5%81%E9%87%8F%22%2C%22%24latest_referrer%22%3A%22https%3A%2F%2Fwww.baidu.com%2F%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk3YTYwMzZiNTI2OGUtMDIzYWI3MDcxN2YzMTNjLTFhNTI1NjM2LTEzMjcxMDQtMTk3YTYwMzZiNTMxNWMzIiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiNTA5MWMyYTQ2YzgxNDJjMTk4MTliYjJkYzhmYTZiNmYifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%225091c2a46c8142c19819bb2dc8fa6b6f%22%7D%2C%22%24device_id%22%3A%22197a6036b5268e-023ab70717f313c-1a525636-1327104-197a6036b5315c3%22%7D',
    'accessToken': 'eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi54d1R2VWQtYnFMV2Z4RS1OMDNSQkF3LjJHVWRjMzhkRGdTQ0hVbkdNbGpYMFdqdy1hMHlTSnBTX0tBZGRwTjdfd2YwN3JYc3llb0h3S1luSmRPRDBhS3dsOWRGUkxUSU5EY1cwNEp5RWw0Z1NUaHl5bU9RUUtlZEJ3anFMUENoWW5MbFhfaHRCZUxnN3VNZW5qQks0M1FXU1V0cHdpSVUxelRWWjN0LXgyN1VDSW9LRUppTXpldWJHOUQzOG5OUGFCaUNpSmV6MzBwQzJCTVc3T1RsNm8zWG1zYmZhZlpYdW81TGZVbmVtSWs3OUh1YU92TU52UkVtVWxzRWlNSDYxNG5pcXFvOU5sLTJFa0I5ZzFWSHUtcFMudXZjMHJhY1cxNWdpMEdZblVzell6UQ.G5m1b86ceGp_UIbQ2pPz5a6B6rS-f6Bc6vDWTOaCrVH_FKcGJZfgK9oZd0L18QfJibcyMEB9u57jqoMWb_ILmQ',
    'creditNo': '%22%22',
    'param_sign': 'jG1fwH',
    'SSO_SESSION_ID': 'MDNkNTZmN2MtMGQ1NC00NmJmLThiZjQtYjczMDhiYzE5MDA1',
    'Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd': '1750839046',
    'x-web-ip': '182.143.132.144, 47.121.110.191, 47.106.31.185, 100.121.99.216',
}

headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'max-age=0',
    'priority': 'u=0, i',
    'referer': 'https://qiye.qizhidao.com/lib/a01b00c00d00e00f00g00h00i00k00/sc2d10dc5af79548fbff85fbd1b22bf982/',
    'sec-ch-ua': '"Chromium";v="136", "Google Chrome";v="136", "Not.A/Brand";v="99"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
    # 'cookie': 'sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkchannel=%7B%22prop%22%3A%7B%22_sa_channel_landing_url%22%3A%22%22%7D%7D; wz_uuid=X/fe36031e2352d91d31adfe63416a305b; Hm_lvt_9ea3e7293b7c088e0d2c88874b63e7dd=1747617767; HMACCOUNT=A735DDA42AC02E6E; SSO_SESSION_ID=ZWVjOGY0MmYtZDExMi00YWZmLTg4ZWQtZDdlNDVkYjMwMWY0; ticket=eyJhbGciOiJIUzUxMiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKa2FYSWlMQ0psYm1NaU9pSkJNVEk0UTBKRExVaFRNalUySW4wLi5odVhicExqVDBmTG1STXQ2b1ZPYnZnLkp2R3BYa2FlcHVaN1ZjUHkySjBheVRNVlZyWURSdmhmazREdWhrc2s2RTQwQWZvVDNhZXA0REkyRVF1ek1zekJOZEM2STFqZzJOSTJjRV9GX3VRZlZDNVZDWEFQSmtrS2tMSTZpSW5CM0FjYU82TFNjV2hrUTVva1htN29UTU9SbjZCVWpmcDdyRnl3RG5XRHo2NDRiSm1vT28xMGx2VnFGczM2OUlmeUltVmlfZjFmMU5GaHVYTk1mSzJrd2lVX2xGaUR5YThmd3d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jRV9GX3VRZlZDNVZDWEFQSmtrS2tMSTZpSW5CM0FjYU82TFNjV2hrUTVva1htN29UTU9SbjZCVWpmcDdyRnl3RG5XRHo2NDRiSm1vT28xMGx2VnFGczM2OUlmeUltVmlfZjFmMU5GaHVYTk1mSzJrd2lVX2xGaUR5YThmd3dLZFpCaG1Wa3NMN3ktWnVMNDIzOWk3aUJYSHpTTkw5NjJSZVI1aTBPNjJyeEk1SUZmeWtrS0IuRGd4aE1TSE5YcHNRdlRiX3VZVXpxUQ.K0Ytme5n24LKre-EXu0nz7CClT1iT2HX_bt_vmFnppc3xwzHCGia43d3WyE3JZVksuo_N5EjcDxj3s3HgI-W8g; creditNo=%22%22; param_sign=roYuB3; Hm_lpvt_9ea3e7293b7c088e0d2c88874b63e7dd=1747619300; smidV2=202505191016307c10a18d5e8a15a50dda3fc1039d489f00ea7a21ddcd9e570; _bl_uid=smmtqayquXdgR4fq7006g2h9IX2I; Hm_lvt_8b5ea374777742fd73d0561bd1dfca6d=1747620994; acw_tc=f5d36357174762107277210433481bd19eb244908197885b08a7a18a2916d7; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%2C%22first_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk2ZTYyMmQ3YzJlN2MtMDI4N2Y4YjIxYzgzYzFlLTI2MDExZjUxLTEzMjcxMDQtMTk2ZTYyMmQ3YzMxYjA1IiwiJGlkZW50aXR5X2xvZ2luX2lkIjoiZjdiMWRjYzBkZGJmNDU1ZDgzM2ZhOTk0MTRmMjc4MGUifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%22f7b1dcc0ddbf455d833fa99414f2780e%22%7D%2C%22%24device_id%22%3A%22196e622d7c2e7c-0287f8b21c83c1e-26011f51-1327104-196e622d7c31b05%22%7D; x-web-ip=171.218.206.136, 47.121.110.187, 47.106.31.167, 100.121.99.209; .thumbcache_de0d870e3139ba2368b2e7ea8f11063c=hZVjd47Cv1sJHhGMmTvVn0f9DpivVn6IF/IytbVBOsjFSd0QEKKRar19TbnFCtp96Hi7/tlo0p6ovKPk4j5lOw%3D%3D; Hm_lpvt_8b5ea374777742fd73d0561bd1dfca6d=1747621872',
}


def get_uuid(url):
    repose = requests.get(cookies=cookies, headers=headers, url=url)

    pattern = r'\(\s*[^)]*?([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})[^)]*?\)'

    matches = re.findall(pattern, repose.text)
    if matches == []:
        with open('./uuid获取错误url.txt', 'a+', encoding='utf-8') as f:
            f.write(f'{url}\n')
        return False
    return matches[0]


def write_zhuanli(items):

    file_exists = os.path.exists('./invebt_number_zhunali.csv')
    df = pd.DataFrame(
        items, columns=['发明授权', '实用新型', '外观设计', '总和', '社会信用统一代码'])
    df.to_csv('invebt_number_zhunali.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("专利信息数据已追加到 invebt_number_zhunali.csv")


def write_rj(items):

    file_exists = os.path.exists('./invebt_number_rj.csv')
    df = pd.DataFrame(
        items, columns=['软件数量', '社会信用统一代码'])
    df.to_csv('invebt_number_rj.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("软件著作权数据已追加到 invebt_number_rj.csv")


def get_patent_number(uuid, lll):
    invent_auth_count = 0
    utility_model_count = 0
    exterior_design = 0
    all_number = 0
    for i in range(2022, 2026):
        json_data_patent = {
            'eid': uuid,
            'apy': i,
            'authority': '',
            'lsc': '授权',
            'pdt': '',
            'pdy': '',
        }

        response = requests.post(
            'https://app.qizhidao.com/qzd-bff-enterprise/qzd/v1/enterprise/pc/patentFilterResult',
            cookies=cookies,
            headers=headers,
            json=json_data_patent,
        )
        # print(response.text)
        # 随机等待时间
        time.sleep(random.uniform(3.2, 4.6))

        data = response.json()
        print(data)
        if data['data']['PDT'] == []:
            invent_auth_count += 0
            utility_model_count += 0
            exterior_design += 0
            continue

        for i in data['data']['PDT']:
            if i['key'] == '发明授权':
                invent_auth_count += int(i['doc_count'])
            elif i['key'] == '实用新型':
                utility_model_count += int(i['doc_count'])
            elif i['key'] == '外观设计':
                exterior_design += int(i['doc_count'])
    all_number = invent_auth_count+utility_model_count+exterior_design
    return [[invent_auth_count, utility_model_count, exterior_design, all_number, lll]]


def main():

    with open("./url_value23.txt", "r", encoding="utf-8") as file:
        urls = [url.strip() for url in file.readlines()]

    with open('./url_value23_code.txt', 'r', encoding='utf-8') as f:
        s_codes = [s_code.strip() for s_code in f.readlines()]

    url_count = 0

    for url, s_code in zip(urls, s_codes):
        

        a = [1,1.5,2,2.5,3,3.5,4]


        b = [4.5,5,5.5,6,7,7.5]

        c = [10,10.5,11,11.5,12,12.5]


        if url_count > 0 and url_count % 10 == 0:
            sleep_time = random.uniform(6, 13.6)  # 随机等待5-10秒
            print(f"已爬取{url_count}个URL，休息{sleep_time:.2f}秒...")
            time.sleep(sleep_time)

        uuid = get_uuid(url)

        if uuid:
            pass
        else:
            print('uuid获取错误')
            continue


        # 每次请求前随机等待0.5-2秒
        request_sleep = random.uniform(2,7.5)
        time.sleep(request_sleep)

        result_zhuanli = get_patent_number(uuid, s_code)
        result_rj = [[0, s_code]]

        write_zhuanli(result_zhuanli)
        write_rj(result_rj)

        url_count += 1


if __name__ == "__main__":
    main()
